import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';

import {
  Row,
  Col,
  Icon,
  Card,
  Tabs,
  Table,
  Radio,
  DatePicker,
  Tooltip,
  Menu,
  Dropdown,
  Statistic,
  Form,
  Button,
} from 'antd';
import numeral from 'numeral';
import {
  ChartCard,
  yuan,
  MiniArea,
  MiniBar,
  MiniProgress,
  Field,
  Bar,
  Pie,
  TimelineChart,
} from 'components/Charts';
import Trend from 'components/Trend';
import NumberInfo from 'components/NumberInfo';

import { dashBoard } from '../../services/api';

import styles from './Analysis.less';

const { TabPane } = Tabs;
const { RangePicker } = DatePicker;

const Yuan = ({ children }) => (
  <span
    dangerouslySetInnerHTML={{ __html: yuan(children) }}
  /> /* eslint-disable-line react/no-danger */
);

const DEFAULT_VALUE = 0;

const FormItem = Form.Item;

@connect(({ chart, loading }) => ({
  chart,
  loading: loading.effects['chart/fetch'],
}))
@Form.create()
export default class Analysis extends Component {
  state = {
    detail: {},
  };

  componentDidMount() {
    const startTime = '2020-01-01T00:00:00Z';
    const endTime = moment().format('YYYY-MM-DD') + 'T00:00:00Z';
    this.init(startTime, endTime);
  }

  async init(startTime, endTime) {
    const params = {
      startTime,
      endTime,
    };
    const response = await dashBoard(params);

    if (response.code === 200) {
      this.setState({
        detail: response.data,
      });
    }
  }

  componentWillUnmount() {}

  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      if (fieldsValue.createTime && fieldsValue.createTime.length) {
        fieldsValue.startTime =
          moment(fieldsValue.createTime[0]).format('YYYY-MM-DD') + 'T00:00:00Z';
        fieldsValue.endTime = moment(fieldsValue.createTime[1]).format('YYYY-MM-DD') + 'T23:59:59Z';
      } else if (!fieldsValue.createTime || !fieldsValue.createTime.length) {
        delete fieldsValue.startTime;
        delete fieldsValue.endTime;
      }

      this.init(fieldsValue.startTime, fieldsValue.endTime);
    });
  };

  renderAdvancedForm() {
    const { getFieldDecorator } = this.props.form;
    return (
      <Form onSubmit={this.handleSearch.bind(this)} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 24 }}>
          <Col md={6} sm={24}>
            <FormItem label="">
              {getFieldDecorator('createTime')(
                <RangePicker style={{ width: '100%' }} placeholder={['开始时间', '结束时间']} />
              )}
            </FormItem>
          </Col>

          <Col md={6} sm={24}>
            <span style={{ float: 'left', marginBottom: 24 }}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  render() {
    const { loaded, detail } = this.state;

    const { loading } = this.props;

    const salesPieData = [
      {
        x: '个人用户数',
        y: detail.personalUserTotal || DEFAULT_VALUE,
      },
      {
        x: '企业用户数',
        y: detail.enterpriseUserTotal || DEFAULT_VALUE,
      },
      {
        x: '服务机构数',
        y: detail.serviceOrgTotal || DEFAULT_VALUE,
      },
      {
        x: '高等院校数',
        y: detail.highSchoolTotal || DEFAULT_VALUE,
      },
      {
        x: '科研机构数',
        y: detail.rdOrgTotal || DEFAULT_VALUE,
      },
    ];

    const salesPieData2 = [
      {
        x: '认证用户数',
        y: detail.authUserTotal || DEFAULT_VALUE,
      },
      {
        x: '非认证用户数',
        y: detail.unAuthUserTotal || DEFAULT_VALUE,
      },
    ];

    const others = [
      {
        x: '专利状态托管数',
        y: (detail.stateMonitorNum || DEFAULT_VALUE) + '件',
      },
      {
        x: '专利年费监管数',
        y: (detail.feeMonitorNum || DEFAULT_VALUE) + '件',
      },
      {
        x: '年费代缴订单量',
        y: (detail.orderTotal || DEFAULT_VALUE) + '单',
      },
      {
        x: '代缴订单总额',
        y: yuan(detail.totalAmount || DEFAULT_VALUE),
      },
      {
        x: '代缴年费总额',
        y: yuan(detail.feeAmount || DEFAULT_VALUE),
      },
      {
        x: '服务费总收入',
        y: yuan(detail.serviceAmount || DEFAULT_VALUE),
      },
    ];

    return (
      <Fragment>
        <div className={styles.tableList}>
          <div className={styles.tableListForm}>{this.renderAdvancedForm()}</div>
        </div>

        <Row
          gutter={24}
          style={{
            marginTop: 24,
          }}
        >
          <Col xl={8} lg={8} md={8} sm={8} xs={8}>
            <Card loading={loading} bordered={true} bodyStyle={{ padding: 10, height: '600px' }}>
              <Pie
                className={styles.myPie}
                hasLegend
                title="总注册用户数"
                subTitle="总注册用户数"
                total={() => (
                  <span
                    dangerouslySetInnerHTML={{
                      __html: salesPieData.reduce((pre, now) => now.y + pre, 0),
                    }}
                  />
                )}
                data={salesPieData}
                valueFormat={val => <span dangerouslySetInnerHTML={{ __html: val }} />}
                height={294}
              />
            </Card>
          </Col>
          <Col xl={8} lg={8} md={8} sm={8} xs={8}>
            <Card loading={loading} bordered={true} bodyStyle={{ padding: 10, height: '600px' }}>
              <Pie
                className={styles.myPie}
                hasLegend
                data={salesPieData2}
                valueFormat={val => <span dangerouslySetInnerHTML={{ __html: val }} />}
                height={294}
              />
            </Card>
          </Col>
          <Col xl={8} lg={8} md={8} sm={8} xs={8}>
            <Card loading={loading} bordered={true} bodyStyle={{ padding: 10, height: '600px' }}>
              {others.map(item => {
                return (
                  <Row gutter={16}>
                    <Col span={24} style={{ margin: 10 }}>
                      <div className="ant-statistic">
                        <div className="ant-statistic-title">{item.x}</div>
                        <div className="ant-statistic-content">
                          <span className="ant-statistic-content-value">
                            <span className="ant-statistic-content-value-int">{item.y}</span>
                          </span>
                        </div>
                      </div>
                    </Col>
                  </Row>
                );
              })}
            </Card>
          </Col>
        </Row>
      </Fragment>
    );
  }
}
